package com.tvunetworks.center.device.service.impl;

import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.device.mapper.UserDeviceMapper;
import com.tvunetworks.center.device.service.TokenService;
import com.tvunetworks.center.device.util.GridMarketResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program:
 * @description:
 * @author HenryChen
 * @create: 7/26/2019 4:02 PM
 **/
@Service
@Slf4j
public class TokenServiceImpl implements TokenService {


    @Value("${gridmarket.tokenPairApi.url}")
    private String gridmarketUrl;


    @Autowired
    RestTemplate restTemplate;


    @Autowired
    private UserDeviceMapper userDeviceMapper;

    /**
     * 调 Grid Market 的接口查看 code 是否合法
     *
     * @param tokenCode
     * @param sid
     * @param jessionId
     * @return
     */
    private Result checkGridTokenCode(String tokenCode, String sid, String jessionId) throws IOException {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        List<String> cookieList = new ArrayList<>();


        cookieList.add("SID=" + sid);
        cookieList.add("JSESSIONID=" + jessionId);

        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("code", tokenCode);

        headers.put(HttpHeaders.COOKIE, cookieList);
        HttpEntity httpEntity = new HttpEntity(param, headers);

        GridMarketResult gridMarketResult = restTemplate.postForObject("http://" + gridmarketUrl +
                "/token/checkGridTokenCode?session={sid}", httpEntity, GridMarketResult.class, sid);

        Result finalResult = new Result()
                .setErrorCode(gridMarketResult.getCode() + "")
                .setErrorInfo(gridMarketResult.getMsg())
                .setResult(gridMarketResult.getData());

        if (gridMarketResult.getCode() == 0) {
            finalResult.setErrorCode(ResultUtil.SUCCESS);
        }

        return finalResult;

    }


    /**
     * // http://10.12.22.93/gridmarket/token/pairGrid?session=1014E41768FB1BA3BF3730AF7AFB0444
     * <p>
     * code: 28714660
     * description: 123123123
     * willAddRIds: 3e3e1aed3a04c722;811c47006d9feec0
     *
     * @param tokenCode
     * @param sid
     * @param jessionId
     * @param description
     * @param willAddRIds
     * @return
     */
    @Override
    public String pairTokenGrid(String tokenCode, String sid, String jessionId, String description, String willAddRIds) throws IOException {

//        Grid market 的配对接口会中包含check，这里不用再check了
//        Result result = checkGridTokenCode(tokenCode, sid, jessionId);
//
//        if(!StringUtils.equals(ResultUtil.SUCCESS,result.getErrorCode())){
//            return JsonUtil.toJsonStr(result);
//        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        List<String> cookieList = new ArrayList<>();


        cookieList.add("SID=" + sid);
        cookieList.add("JSESSIONID=" + jessionId);

        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("code", tokenCode);
        param.add("description", description);
        param.add("willAddRIds", willAddRIds);

        headers.put(HttpHeaders.COOKIE, cookieList);
        HttpEntity httpEntity = new HttpEntity(param, headers);

        ResponseEntity<GridMarketResult> gridMarketResultResponseEntity = null;
        GridMarketResult  gridMarketResult;
        Result finalResult = new Result();
        try {
            gridMarketResultResponseEntity = restTemplate.postForEntity("http://" + gridmarketUrl + "/token/pairGrid?session={sid}",
                    httpEntity, GridMarketResult.class, sid);
        } catch (RestClientException e) {
            finalResult.setErrorCode("-2")
                    .setErrorInfo("Failed :"+e.getMessage());
            return JsonUtil.toJsonStr(finalResult);
        }

        if(gridMarketResultResponseEntity.getStatusCode() == HttpStatus.OK){
            gridMarketResult = gridMarketResultResponseEntity.getBody();
            if (gridMarketResult!=null){
                finalResult.setErrorCode(gridMarketResult.getCode() + "")
                        .setErrorInfo(gridMarketResult.getMsg())
                        .setResult(gridMarketResult.getData());
            }
            if (StringUtils.pathEquals("0", finalResult.getErrorCode())) {
                finalResult.setErrorCode(ResultUtil.SUCCESS);
            }
        } else {
            finalResult.setErrorCode("-1")
                    .setErrorInfo("Failed");
            log.error("token/pairGrid error code [{}],data: [{}]",gridMarketResultResponseEntity.getStatusCode(),gridMarketResultResponseEntity.toString());
        }

        return JsonUtil.toJsonStr(finalResult);

    }

    @Override
    public List<String> listTTokenPairR(String tId) throws IOException {
        return userDeviceMapper.listTTokenPairR(tId);
    }

}
